package com.atguigu.edu.realtime.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class DimUtil {
    
    public static JSONObject readDimFromPhoenix(Connection conn,
                                                String tableName,
                                                String id) throws SQLException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //执行查询语句   id=10' or 1=1 // where id=10 or 1=1
        String sql = "select * from " + tableName + " where id=?";
        // 根据 id 查找的维度信息, 所以只有一条
        List<JSONObject> list = JdbcUtil.queryList(conn, sql, new String[]{id}, JSONObject.class, false);
        if (list.size() == 0) {
            System.out.println("维度表: " + tableName + ", id= " + id + " 中没有查到数据, 请检测");
        }
        return list.get(0); // 如果这里报越界, 则是因为你的维度表中没有数据. 使用 maxwell-bootstrap 同步下维度数据
    }
    
    public static JSONObject readDim(Jedis redisClient,
                                     Connection conn,
                                     String tableName,
                                     String id) throws SQLException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // 1. 从 redis 读取维度数据
        JSONObject dim = readDimFromRedis(redisClient, tableName, id);
        // 2. 如果读到, 则直接返回
        if (dim == null) {
            // 3. 如果没有读到则从 phoenix 读取, 返回
            dim = readDimFromPhoenix(conn, tableName, id);
            // 4. 把读到的结果再写入到 redis
            writeDimToRedis(redisClient, tableName, id, dim);
            System.out.println("走的数据库:" + tableName + "  " + id);
        }else {
            System.out.println("走的缓存:" + tableName + "  " + id);
        }
        
        return dim;
    }
    
    // TODO
    private static void writeDimToRedis(Jedis redisClient, String tableName, String id, JSONObject dim) {
        String key = tableName + ":" + id;
        /*redisClient.set(key, dim.toJSONString()); // 写入到 string 中
        redisClient.expire(key, 2 * 24 * 60 * 60);*/
    
        redisClient.setex(key, 2 * 24 * 60 * 60, dim.toJSONString());
    }
    
    // TODO
    private static JSONObject readDimFromRedis(Jedis redisClient, String tableName, String id) {
        String key = tableName + ":" + id;
        String json = redisClient.get(key);
        // json有可能是 null
        if (json != null) {
            return JSON.parseObject(json);
        }
        return null;
    }
}
